/*
 * Created on Mar 23, 2006
 *
 */
package org.mushroomdb.triggers;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.mushroomdb.catalog.Catalog;
import org.mushroomdb.catalog.Table;
import org.mushroomdb.service.Service;

/**
 * @author mchiodi
 */
public class TriggersService implements Service {
	private Map triggers;
	private Map triggersByName;
	private Map tables;

	/**
	 * Constructs the TriggersService.
	 */
	public TriggersService() {
		super();
		this.triggers = new HashMap();
		this.triggersByName = new HashMap();
		this.tables = new HashMap();
	}
	
	/**
	 * 
	 * @param trigger
	 */
	public void addTrigger(Trigger trigger, Table table) {
		Set set = (Set) this.triggers.get(table.getName());
		if (set == null) {
			set = new LinkedHashSet();
			this.triggers.put(table.getName(),set);
		}
		set.add(trigger);
		
		this.triggersByName.put(trigger.getName(),trigger);
		this.tables.put(trigger,table.getName());
	}
	
	/**
	 * 
	 * @param trigger
	 * @return
	 */
	public boolean removeTrigger(Trigger trigger, Table table) {
		Set set = (Set) this.triggers.get(table.getName());
		if (set != null) {
			this.triggersByName.remove(trigger.getName());
			this.tables.remove(trigger);
			return set.remove(trigger);
		} else {
			return false;
		}
	}
	
	/**
	 * 
	 * @param table
	 * @return
	 */
	public Iterator getTriggers(Table table) {
		Set set = (Set) this.triggers.get(table.getName());
		if (set == null) {
			return Collections.EMPTY_SET.iterator();
		} else {
			return set.iterator();
		}
	}
	
	/**
	 * 
	 * @param name
	 * @return
	 */
	public Trigger getTrigger(String name) {
		return (Trigger) this.triggersByName.get(name);
	}
	
	/**
	 * 
	 * @param trigger
	 * @return
	 */
	public Table getTable(Trigger trigger) {
		String tableName = (String) this.tables.get(trigger);
		return (Table) Catalog.getInstance().getTableByName(tableName);
	}

	/* (non-Javadoc)
	 * @see org.mushroomdb.service.Service#initialize()
	 */
	public void initialize() {
		// TODO Crear tabla para triggers si no existe y cargarlos.
	}

}
